package com.zhiyun.hxzy.controller.admin;

import com.zhiyun.hxzy.domain.HeaderImg;
import com.zhiyun.hxzy.domain.queryvo.Result;
import com.zhiyun.hxzy.service.HeaderImgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/admin/headerImg")
public class HeaderImgController {
    @Autowired
    private HeaderImgService headerImgService;

    @RequestMapping("/whole")
    public ModelAndView findAll(@RequestParam(defaultValue = "0") int pageNum, @RequestParam(defaultValue = "5") int pageSize){
        Page<HeaderImg> headerImgs = headerImgService.findAll (pageNum-1, pageSize);
        ModelAndView modelAndView=new ModelAndView ();
        modelAndView.getModelMap ().addAttribute ("headerImgs",headerImgs);
        modelAndView.setViewName ("admin/headerimg_list");
        return modelAndView;
    }

    @RequestMapping("/addHeaderImg")
    public String addHeaderImg(HeaderImg headerImg, HttpServletRequest request){
        headerImgService.addHeaderImg (headerImg);
        return "redirect:"+request.getContextPath ()+"/admin/headerImg/whole";
    }

    @RequestMapping("/deleteHeaderImg")
    public String deleteHeaderImg(Long[] ids, HttpServletRequest request){
        headerImgService.deleteHeaderImg (ids);
        String referer = request.getHeader("referer");
        return "redirect:"+referer;
    }

    @RequestMapping("/updateHeaderImg")
    public String updateHeaderImg(Long[] ids, HttpServletRequest request){
        headerImgService.updateHeaderImg (ids);
        String referer = request.getHeader("referer");
        return "redirect:"+referer;
    }

    @RequestMapping("/upload")
    public @ResponseBody Result upload(MultipartFile file) throws Exception {
        return headerImgService.update (file);
    }

    @RequestMapping("/updateHeaderImg2")
    public String update(Long id, Model model){
        model.addAttribute("headerImg", headerImgService.findById(id));
        return "./admin/headerImg_update";
    }

    @RequestMapping("/addorUpdate")
    public String addorUpdate(HeaderImg headerImg,HttpServletRequest request){
        headerImgService.addorUpdate(headerImg);
        return "redirect:"+request.getContextPath ()+"/admin/headerImg/whole";
    }
}